package com.kgcx.price.utils;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.utils.UUIDUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class MqttServiceUtil
{
    @Value("${kgcx.mqtt.url:tcp://120.78.159.128:1883}")
    private String hostUrl ;

    @Value("${kgcx.mqtt.username:kgcx_price}")
    private String userName;

    @Value("${kgcx.mqtt.password:kgcx@123}")
    private String passWord;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final Logger logger = LoggerFactory.getLogger(MqttServiceUtil.class);

//    private static final String clientid = ;

    private MqttTopic topic;

    private MqttMessage message;

    public void init() throws MqttException {
        //MemoryPersistence设置clientid的保存形式，默认为以内存保存
        MqttClient client = new MqttClient(hostUrl, String.valueOf(System.currentTimeMillis()), new MemoryPersistence());
        connect(client);
    }

    private void connect(MqttClient client) {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new DriverPushCallback(stringRedisTemplate));
            client.connect(options);
            topic = client.getTopic("mileageRecordUpload/"+ System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("mqtt服务端连接失败：" + e.getMessage());
        }
    }

    private void publish(MqttMessage message) throws MqttException{
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        logger.info(token.isComplete()+"========");
    }

    /**
     * mqtt 推送消息方法
     *
     * @param  qos 发布消息服务质量(至多一次 Qos level=0, 至少一次Qos level=1. 只有一次Qos level=2)
     * @param  retained 是否是实时发送的消息(false=实时，true=服务器上保留的最后消息)
     * @param  payload 消息内容
     * @return
     */
    public ReturnData doPublish(int qos, Boolean retained, String payload, MqttServiceUtil server)
    {
        try
        {
            server.message = new MqttMessage();
            server.message.setQos(qos);
            server.message.setRetained(retained);
            if(StringUtils.isEmpty(payload))
            {
                server.message.setPayload("".getBytes());
            }
            else
            {
                server.message.setPayload(payload.getBytes());
            }
            server.publish(server.message);
        }
        catch (MqttException e)
        {
            e.printStackTrace();
            logger.error("mqtt服务端生产数据失败：" + e.getMessage());
            return new ReturnData(SystemVariable.ERROR_RETURN_CODE, "mqtt服务端推送数据失败：" + e.getMessage());
        }

        return new ReturnData(SystemVariable.SUCCESS_RETURN_CODE, "mqtt服务端推送数据成功");
    }

}
